#!/usr/bin/env python

import component
import resource.string.app as r

from ..._console import Console

class Sweeper(Console):

    def run(self):
        self.greeting(r)
        
        if self.isRunning(r.name):
            self.info('%s is already running.\n' % r.name)
            self.info('Please wait a moment and try again.\n')
        else:
            rpu = self.loadRpu()
            if rpu:
                self.sweep(rpu)
                rpu.close()
            
        self.farewell()
        
    def loadRpu(self):
        port = self._args.port
        self.verbose('Serial Port: %s' % port)
        
        baudrate = self._args.baudrate
        self.verbose('Serial Port Baudrate: %s' % baudrate)
        
        try:
            timeout = self._args.timeout
            rpu = component.Rpu(port, baudrate, timeout=timeout)
        except:
            rpu = None
            self.verbose('Error creating serial port instance.\n')
        else:
            self.verbose('Serial port instance created.\n')
        return rpu

    def sweep(self, rpu):
        for device in self._args.devices:
            self.progress('Sweeping device %d... ' % device)
            
            rpu.flush()
            measurements = rpu.flare(device)
            
            if measurements:
                self.success('OK ^_^\n')
                s = 'Save data device %d to server...\n'
                for measurement in measurements:
                    self.info(s % measurement.device)
                    measurement.bulk(self._args.host)
                    self.success('OK ^_^\n')
            else:
                self.fail('Error >_<\n')

